<?php
/**
 * Project: HTPHouDuan
 * User: xilibo
 * Date: 2018/1/30 0030
 */

namespace app\api\controller;

use think\Config;
use think\Cache;
use app\common\controller\CommonController;

class UserAuthController extends CommonController
{

    /**
     * 与网关、前端通信用的code
     */
    public function code()
    {
        $loginInfo['username'] = $this->request->param('gw_username', '');
        $loginInfo['code'] = str_replace(' ', '+', $this->request->param('code', ''));
//        $loginInfo['node'] = $this->request->param('node', '');
        if (!empty($loginInfo['username'] && !empty($loginInfo['code']))) {
            $this->encryptedParams = $loginInfo;
            static::$secKey = Config::get('api.secret_key', '');
            if (empty(static::$secKey)) {
                $this->jsonError('secret_key_error', 503);
            }

            $mcrypter = self::getMcrypter();
            $username = $loginInfo['username'];
            //网关与API端通信code参数解密
            $code = $mcrypter->decrypt($loginInfo['code']);
            if (empty($code)) {
                $this->jsonError('user_code_error');
            }

            $userModel = model('user');
            $userInfo = $userModel->getRow(['user_login' => $username]);
            $ckCodeUser = 'code.' . $code . '.user';
            $ckUserCode = 'user.' . $username . '.code';
            $codeExpire = config('api.cache_code_expire');
            if (empty($userInfo)) {
                $userInfo = ['user_login' => $username, 'user_pass' => uniqid()];
                if (! $userModel->saveUser($userInfo)){
                    return  $this->jsonError('user_register_fail');
                }

                $userInfo = $userModel->getRow(['user_login' => $username]);
            }

            if (isset($userInfo['password'])) unset($userInfo['password']);
            Cache::set($ckCodeUser, $userInfo, $codeExpire);
            Cache::set($ckUserCode, $code, $codeExpire);

            return $this->jsonSuccess('设定成功');
        } else {
            return $this->jsonError('用户登陆信息不能为空');
        }

    }

    /**
     * 用户授权
     */
    public function auth()
    {
        if (! $this->verifyLogin()){
            return $this->jsonError('authorize_fail');
        }

        return $this->jsonSuccess('授权成功');
    }

}